package com.yxsk.relay.job.admin.core.collector;

import com.yxsk.relay.job.admin.core.schedule.JobTriggerInfo;
import com.yxsk.relay.job.admin.data.entity.JobExecuteLog;
import com.yxsk.relay.job.admin.data.service.JobExecuteLogService;
import com.yxsk.relay.job.component.admin.utils.SpringBeanUtils;
import com.yxsk.relay.job.component.common.exception.RelayJobRuntimeException;
import com.yxsk.relay.job.component.common.vo.ExecuteResult;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author 11376
 * @CreaTime 2019/8/5 23:14
 * @Description
 */
public class QuartzAsyncJobResultCollector implements JobResultCollector {

    // 任务计算实现者
    private JobResultCollector collector;

    private JobTriggerInfo triggerInfo;

    public QuartzAsyncJobResultCollector(JobResultCollector collector, JobTriggerInfo triggerInfo) {
        Assert.notNull(collector, "Collector not be null");
        this.collector = collector;
        this.triggerInfo = triggerInfo;
    }

    @Override
    public void collect(JobTriggerInfo triggerInfo) {
        // 调用实现者
        collector.collect(triggerInfo);
    }

    public interface ExecuteCompleteCallback {

        void callback();

    }

    public class DefaultExecuteCompleteCallback implements ExecuteCompleteCallback {

        @Override
        public void callback() {
            // 查询是否所有任务都已完成
            List<JobExecuteLog> logList = SpringBeanUtils.getBean(JobExecuteLogService.class).findByTriggerId(triggerInfo.getTriggerId());

            if (CollectionUtils.isEmpty(logList)) {
                // 无执行日志但是有回调, 异常
                throw new RelayJobRuntimeException("Empty job execute log");
            }

            for (JobExecuteLog executeLog : logList) {
                if (ExecuteResult.ExecuteResultCode.EXECUTING.getCode().equals(executeLog.getExecuteStatus())) {
                    // 存在执行中的任务
                    return;
                }
            }

            // 任务都已完成, 执行任务结果处理
            collect(triggerInfo);
        }
    }

}
